package at.fhj.itm11.forum.beans;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.inject.Inject;

import at.fhj.itm11.forum.data.PostRepository;
import at.fhj.itm11.forum.data.TopicRepository;
import at.fhj.itm11.forum.model.Post;
import at.fhj.itm11.forum.model.Topic;
import at.fhj.itm11.forum.model.User;
import at.fhj.itm11.forum.service.RatingService;
import at.fhj.itm11.forum.util.ForumConstants;

@ManagedBean
@ViewScoped
public class ShowPostsBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8433063884320342294L;

	@Inject
	private TopicRepository topicRepo;
	
	@Inject
	private TopicBean topicBean;

	@Inject
	private PostRepository postRepository;

	@Inject
	private RatingService ratingService;

	@Inject
	private AuthenticationBean authBean;

	private DataModel<Post> postModel;

	private List<Post> posts;
	private Topic topic;
	private User user;

	@PostConstruct
	public void init() {
		String topicIdString = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap().get("id");
		if (topicIdString != null) {
			Long topicId = Long.valueOf(topicIdString);
	
			Topic currentTopic = topicRepo.findById(topicId);
			
			if (currentTopic != null) {
				topicBean.setCurrentTopic(currentTopic);
				posts = loadPosts(currentTopic);
			}
	
			postModel = new ListDataModel<Post>(posts);
		}
	}

	public List<Post> loadPosts(Topic topic) {
		this.setTopic(topic);
		posts = postRepository.findPostsByTopic(topic.getId());
		user = (User) authBean.getSession().getAttribute(
				ForumConstants.SESSION_CURRENT_USER);
		authBean.getSession().setAttribute(
				ForumConstants.SESSION_CURRENT_TOPIC, topic);

		for (Post p : posts) {
			int[] ratingStatistic = ratingService
					.getRatingStatistics(p.getId());

			p.setPercentageOfPositiveRatings(ratingStatistic[0]);
			p.setPercentageOfNegativeRatings(ratingStatistic[1]);
		}
		return posts;
	}

	public List<Post> getPosts() {
		return posts;
	}

	public void setPosts(List<Post> posts) {
		this.posts = posts;
	}

	public Topic getTopic() {
		return topic;
	}

	public void setTopic(Topic topic) {
		this.topic = topic;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public DataModel<Post> getPostModel() {
		return postModel;
	}

	public void setPostModel(DataModel<Post> postModel) {
		this.postModel = postModel;
	}

}
